import { addRule } from '@/services/ant-design-pro/api';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { ActionType, ModalForm, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton } from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, Upload, UploadFile, message } from 'antd';
import { FC, useState } from 'react';
import OSS from 'ali-oss';
import { getOssSecurity, upSeries } from '@/services/ant-design-pro/source';
import { AesDecrypt } from '@/utils/aes';
import dayjs from 'dayjs';

interface CreateFormProps {
  reload?: ActionType['reload'];
  id?: string;
  values: any;
}

const CreateForm: FC<CreateFormProps> = (props) => {
  const { reload, values } = props;

  const [messageApi, contextHolder] = message.useMessage();
  const [cover, setCover] = useState<string>();
  const [fileList, setFileList] = useState<UploadFile[]>(values.cover ==='' ? [] : [ {
    uid: '1',
    name: values.cover,
    status: 'done',
    url: cover,
  }]);
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const { run, loading } = useRequest(upSeries, {
    manual: true,
    onSuccess: () => {
      messageApi.success('更新成功');
      reload?.();
    },
    onError: () => {
      messageApi.error('更新失败');
    },
  });
  const uploadOss = async(e:any) =>{
    const {obj} = await getOssSecurity();
    const ossDt = JSON.parse(AesDecrypt(obj));
    const fileNameArray = e.file.name.split('.');
    const names = encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-11)
    const fileName = names + '.'+fileNameArray[1];
    const date = dayjs(new Date().getTime()).format('YYYYMM');
    const client = new OSS({
      region: 'oss-cn-shenzhen',
      bucket: 'ky-data',
      accessKeyId: ossDt.accessKeyId,
      accessKeySecret: ossDt.accessKeySecret,
      stsToken: ossDt.securityToken,
      secure: true,
    });
    if(e.file.type === 'image/jpeg' || e.file.type === 'image/png' || e.file.type === 'image/gif' || e.file.type === 'image/jpg'){
      const {name, res, url} = await client.put(`/cover/${date}/`+fileName, e.file);
      const localUrl = window.URL.createObjectURL(e.file);
      if(res.status === 200){
        setFileList([
          {
            uid: '1',
            name: name,
            status: 'done',
            url: localUrl,
          },
        ])
        setCover(url);
      }
    }
  }
  const handleChange = (info: any) =>{
    const {file} = info;
    const { status } = file;
    const date = dayjs(new Date().getTime()).format('YYYYMM');
    const fileNameArray = file.name.split('.');
    const name = encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-11);
    if (status === 'removed') {
      setFileList([]);
      setCover('');
    }
  }
  const beforeCoverUpload = (file: any, fileList:any) => {
    const isPdf  = (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg');
    if (!isPdf) {
      message.error(`请上传png/jpg/jpeg文件`);
    }
    return isPdf;
  }

  return (
    <>
      {contextHolder}
      <ModalForm
        title='编辑系列'
        trigger={
          <Button type="link">
            修改
          </Button>
        }
        width="400px"
        modalProps={{ okButtonProps: { loading }, destroyOnClose: true  }}
        onFinish={async (value) => {
          const params = {
            "name": value.name,
            "descrip": value.descrip,
            "cover": cover ?? '',
            "typeId": values.typeId,
            'id': values.id,
            'status': value.status
          }
          await run(params);
          return true;
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.searchTable.ruleName"
                  defaultMessage="Rule name is required"
                />
              ),
            },
          ]}
          label='系列名称'
          width="md"
          name="name"
          initialValue={values.name}
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.searchTable.ruleName"
                  defaultMessage="Rule name is required"
                />
              ),
            },
          ]}
          label='系列简介'
          width="md"
          name="descrip"
          initialValue={values.description}
        />
        <ProFormSelect
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="pages.searchTable.ruleName"
                  defaultMessage="Rule name is required"
                />
              ),
            },
          ]}
          label='状态'
          width="md"
          name="status"
          initialValue={{label: values.status === 1 ? '开启' : '关闭', value: values.status}}
          request={async () => {
            return [
              {label: '开启', value: 1},
              {label: '关闭', value: 0}
            ]
          }}
        />
        <Upload
          customRequest = {uploadOss}
          fileList={fileList}
          maxCount={1}
          listType='picture'
          onChange={(info) => {handleChange(info)}}
          beforeUpload={(file, fileList)=>{beforeCoverUpload(file, fileList)}}
        >
          <Button icon={<UploadOutlined />}>上传封面</Button>
        </Upload>
      </ModalForm>
    </>
  );
};

export default CreateForm;
